package com.jiawa.train.gateway.config;

import com.jiawa.train.gateway.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {

    Logger LOG = LoggerFactory.getLogger(LoginMemberFilter.class);

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    private static final String[] WHITE_LIST = {"/member/member/register", "/member/member/login", "/member/member/send-code"};


    private boolean isPathInWhiteList(String path) {
        if (path.contains("/admin")) {
            return true;
        }
        for (String whitePath : WHITE_LIST) {
            if (PATH_MATCHER.match(whitePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String path = exchange.getRequest().getURI().getPath();

        if (isPathInWhiteList(path)) {
            LOG.info("不需要验证登录: {}", path);
            return chain.filter(exchange);
        } else {
            LOG.info("需要验证登录: {}", path);
        }

        String token = exchange.getRequest().getHeaders().getFirst("token");

        LOG.info("会员登录开始: {}",  token);

        if (token == null || token.isEmpty()) {
            LOG.info("登录验证失败: {}", token);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        Boolean pass = JwtUtil.validate(token);

        if (pass) {
            LOG.info("登录验证通过: {}", token);
            return chain.filter(exchange);
        } else {
            LOG.info("登录验证失败: {}", token);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
